﻿using PMS.Common;
using PMS.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.DS
{
    public partial class DataAnalysAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {

                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取所有合同的年度范围
        /// </summary>
        public void GetSaleYears()
        {
            var list = DALSession.Current.View_DS_SaleAnalyseDAL.GetListBy(sa => sa.Year != null);
            SortedSet<String> res = new SortedSet<string>();
            list.ForEach(li => res.Add(li.Year));
            List<DSYearChose> years = new List<DSYearChose>();
            foreach (var item in res)
            {
                DSYearChose dsy = new DSYearChose();
                dsy.value = item;
                dsy.text = item;
                years.Add(dsy);
            }
            Response.Write(JsonHelper.toJson(years));
        }

        /// <summary>
        /// 获取所有生产订单的年度范围
        /// </summary>
        public void GetProdYears()
        {
            var list = DALSession.Current.View_DS_ProductionAnalyseDAL.GetListBy(sa => sa.YearMonth != null);
            SortedSet<String> res = new SortedSet<string>();
            list.ForEach(li => res.Add(li.YearMonth));
            List<DSYearChose> years = new List<DSYearChose>();
            foreach (var item in res)
            {
                DSYearChose dsy = new DSYearChose();
                dsy.value = item;
                dsy.text = item;
                years.Add(dsy);
            }
            Response.Write(JsonHelper.toJson(years));
        }

        /// <summary>
        /// 获取所有的合同，按月和客户进行分组
        /// </summary>
        public void GetSaleDatas()
        {
            String year = Request.Form["year"];
            var list = DALSession.Current.View_DS_SaleAnalyseDAL.GetListBy(sa => sa.Year == year);
            SortedSet<String> months = new SortedSet<string>();
            list.ForEach(li => months.Add(li.Month));
            List<String> monItems = months.ToList();
            List<MonthData> monthData = new List<MonthData>(monItems.Count);
            List<SeriesData> seriesData = new List<SeriesData>(monItems.Count);
            ChartDataForSale cdfs = new ChartDataForSale();
            cdfs.monthData = monthData;
            cdfs.seriesData = seriesData;
            for (int i = 0; i < monItems.Count; i++)
            {
                MonthData md = new MonthData();
                md.name = monItems[i];
                md.y = 0;
                md.drilldown = monItems[i];
                SeriesData sd = new SeriesData();
                sd.name = monItems[i];
                sd.id = monItems[i];
                sd.data = new List<PMS.Model.SeriesData.seriesData>();
                monthData.Add(md);
                seriesData.Add(sd);
                list.ForEach(
                    li =>
                    {
                        if (li.Month == monItems[i])
                        {
                            md.y += (decimal)li.MonthSale;
                            PMS.Model.SeriesData.seriesData temp = new SeriesData.seriesData();
                            temp.cName = li.ComName;
                            temp.money = (decimal)li.MonthSale;
                            sd.data.Add(temp);
                        }
                    }
                    );
            }
            Response.Write(JsonHelper.toJson(cdfs));
        }

        /// <summary>
        /// 获取所有订单，按日和客户进行分组
        /// </summary>
        public void GetProdData()
        {
            String yearMonth = Request.Form["yearMonth"];
            var list = DALSession.Current.View_DS_ProductionAnalyseDAL.GetListBy(sa => sa.YearMonth == yearMonth);
            SortedSet<String> days = new SortedSet<string>();
            list.ForEach(li => days.Add(li.Day));
            List<String> dayItems = days.ToList();
            List<MonthData> monthData = new List<MonthData>(dayItems.Count);
            List<ProdSeriesData> seriesData = new List<ProdSeriesData>(dayItems.Count);

            ChartDataForProd cdfs = new ChartDataForProd();
            cdfs.monthData = monthData;
            cdfs.seriesData = seriesData;
            for (int i = 0; i < dayItems.Count; i++)
            {
                MonthData md = new MonthData();
                md.name = dayItems[i] + "日";
                md.y = 0;
                md.drilldown = dayItems[i];
                ProdSeriesData sd = new ProdSeriesData();
                sd.name = dayItems[i];
                sd.id = dayItems[i];
                sd.data = new List<ProdSeriesData.seriesData>();
                monthData.Add(md);
                seriesData.Add(sd);
                list.ForEach(
                    li =>
                    {
                        if (li.Day == dayItems[i])
                        {
                            md.y += (decimal)li.CompletedNum;
                            ProdSeriesData.seriesData temp = new ProdSeriesData.seriesData();
                            temp.cName = li.CustomerName;
                            temp.deliveryNum = (int)li.CompletedNum;
                            sd.data.Add(temp);
                        }
                    }
                    );
            }
            Response.Write(JsonHelper.toJson(cdfs));
        }

        /// <summary>
        /// 获取年度销售合同报表
        /// </summary>
        public void GetContractList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault().Field = "SignDate";
                }
                if (listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault().Field = "SignDate";
                }
            }
            Expression<Func<View_DS_SaleAnalyseReport, bool>> exp = SearchExpression.FindByGroup<View_DS_SaleAnalyseReport>(listSearch);
            string OrderId = OperateContext.Sort == null ? "ID" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_DS_SaleAnalyseReportDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OperateContext.Order);
            count = DALSession.Current.View_DS_SaleAnalyseReportDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        public void SaleAnalyse2Excel()
        {
            //1.首先获取要导出的实体数据集合list
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startSignDate").FirstOrDefault().Field = "SignDate";
                }
                if (listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endSignDate").FirstOrDefault().Field = "SignDate";
                }
            }
            Expression<Func<View_DS_SaleAnalyseReport, bool>> exp = SearchExpression.FindByGroup<View_DS_SaleAnalyseReport>(listSearch);
            string OrderId = OperateContext.Sort == null ? "ID" : OperateContext.Sort;
            var list = DALSession.Current.View_DS_SaleAnalyseReportDAL.GetListBy(exp);
            // 2.设置单元格抬头
            // key：实体对象属性名称，可通过反射获取值
            // value：Excel列的名称
            string cellhead = Request.Form["cellhead"];
            JavaScriptSerializer serial = new JavaScriptSerializer();
            Dictionary<string, string> JsonData = serial.Deserialize<Dictionary<string, string>>(cellhead);
            // 3.进行Excel转换操作，并返回转换的文件下载链接
            string urlPath = ExcelHelper.EntityListToExcel2003(JsonData, list, "销售报表");
            Response.Write(JsonHelper.toJson(urlPath)); // 返回Json格式的内容
        }

        /// <summary>
        /// 获取年度生产订单报表
        /// </summary>
        public void GetProductionList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startCompletedDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startCompletedDate").FirstOrDefault().Field = "CompletedDate";
                }
                if (listSearch.Where(s => s.Field == "endCompletedDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endCompletedDate").FirstOrDefault().Field = "CompletedDate";
                }
            }
            Expression<Func<View_DS_ProductionAnalyse, bool>> exp = SearchExpression.FindByGroup<View_DS_ProductionAnalyse>(listSearch);
            string OrderId = OperateContext.Sort == null ? "CompletedDate" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_DS_ProductionAnalyseDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, false);
            count = DALSession.Current.View_DS_ProductionAnalyseDAL.GetCount(exp);
            //查询全部合计，不然是以每页进行合计
            int totalNum = 0;
            string strWhere = SearchExpression.conStrBySearch(listSearch);
            string sql = "  select SUM(CompletedNum) AS CompletedNum  FROM  View_DS_ProductionAnalyse where" + strWhere;
            DataTable dt = SqlHelper.GetDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                string completedNum = dt.Rows[0]["CompletedNum"].ToString();
                totalNum = completedNum == "" ? 0 : Convert.ToInt32(completedNum);
            }
            //footer要为json数组，这里用list
            List<object> footList = new List<object> 
            {    
                new {CompletedDate="合计：", CompletedNum = totalNum, ProductName="", TechParams=""},
            };
            Response.Write(JsonHelper.toPageJsonFooter(list, count, footList));
        }

        /// <summary>
        /// 导出生产报表excel
        /// </summary>
        public void ProductionAnalyse2Excel()
        {
            //1.首先获取要导出的实体数据集合list
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startCompletedDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startCompletedDate").FirstOrDefault().Field = "CompletedDate";
                }
                if (listSearch.Where(s => s.Field == "endCompletedDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endCompletedDate").FirstOrDefault().Field = "CompletedDate";
                }
            }
            Expression<Func<View_DS_ProductionAnalyse, bool>> exp = SearchExpression.FindByGroup<View_DS_ProductionAnalyse>(listSearch);
            string OrderId = OperateContext.Sort == null ? "CompletedDate" : OperateContext.Sort;
            var list = DALSession.Current.View_DS_ProductionAnalyseDAL.GetListBy(exp);
            // 2.设置单元格抬头
            // key：实体对象属性名称，可通过反射获取值
            // value：Excel列的名称
            string cellhead = Request.Form["cellhead"];
            JavaScriptSerializer serial = new JavaScriptSerializer();
            Dictionary<string, string> JsonData = serial.Deserialize<Dictionary<string, string>>(cellhead);
            // 3.进行Excel转换操作，并返回转换的文件下载链接
            string urlPath = ExcelHelper.EntityListToExcel2003(JsonData, list, "生产日报表");
            Response.Write(JsonHelper.toJson(urlPath)); // 返回Json格式的内容
        }
    }
}